<?php

namespace App\Models;

class WxTpl extends BaseModel
{
    protected $tempId = [
        'new_order' => 'oy5RGXCiU3_MNun36SW8QUWsFk3SXfK7eXa5hPxeATE',
        'pre_send' => '4KCFMdfg_5sZUhVjQZ-AmJU175EmrH2oMwszaLIVC1E',
        'com_send' => 'rBs6-hwb4IWUVhL7zURYHAoX0Op9zbmTBxVFhU0Qrlc',
        'rec_send' => 'VSwOGU4F8CNrsXyD10etQMcKvF7ULz7ScffXEo64Jas'
    ];

    //新订单提醒（送水工）
    function newOrderMsg($orderData, $shopId, $resend = 0)
    {
        if ($_SERVER['SERVER_NAME'] == 'www.qds.cn') {
            return true;
        }
        $worker = new Worker();
        $workers = $worker->_redisGetWorkerList($shopId);
        $tmpId = $this->tempId['new_order'];

        $wechatSet = new WechatSet();
        $settings = $wechatSet->_getOne(['admin_id' => 1]);
        if (!$settings) {
            return false;
        }
        config(['wechat.app_id' => $settings['wx_app_id']]);
        config(['wechat.secret' => $settings['wx_app_secret']]);
        config(['wechat.aes_key' => $settings['wx_aes_key']]);

        $wechat = app('wechat');
        $url = url('/') . '/manager/order-list.html';
        $type = '微信支付';
        if ($orderData['type']) {
            $type = '货到付款';
        }
        if (!$orderData['type'] && $orderData['bill_id']) {
            $type = '水票支付';
        }
//        $member = new Member();
//        $memberCache = $member->_redisGetOneByMid($orderData['buyer_id']);
//        $memberInfo = '';
//        if ($memberCache && $memberCache['wx_openid']) {
//            $memberInfo = $member->_redisGetOneByWxOpenId($memberCache['wx_openid'],$orderData['shop_id']);
//        }
//        if ($memberInfo && isset($memberInfo['worker_id']) && $memberInfo['worker_id']) {
//            $workerInfo = $worker->_redisGetOneByWid($memberInfo['worker_id']);
//            if ($workerInfo['openid'] && $workerInfo['status']) {
//                try {
//                    $wechat->notice->send([
//                        'touser' => $workerInfo['openid'],
//                        'template_id' => $tmpId,
//                        'url' => $url,
//                        'data' => [
//                            'first' => "新送水订单待处理 ( $type )",
//                            'keyword1' => date('Y年m月d日 H:i', $orderData['addtime']),
//                            'keyword2' => $orderData['goods_name'],
//                            'keyword3' => $orderData['bucket_num'],
//                            'keyword4' => $orderData['buyer_address'],
//                            'keyword5' => $orderData['description'],
//                            'remark' => '请尽快接单送水。',
//                        ],
//                    ]);
//                } catch (\Exception $e) {
//                    return false;
//                }
//            }
//        } else {
        foreach ($workers as $v) {
            $workerInfo = $worker->_redisGetOneByWid($v['id']);
            if ($workerInfo['openid'] && $workerInfo['status']) {
                try {
                    $wechat->notice->send([
                        'touser' => $workerInfo['openid'],
                        'template_id' => $tmpId,
                        'url' => $url,
                        'data' => [
                            'first' => "新送水订单待处理 ( $type )",
                            'keyword1' => date('Y年m月d日 H:i', $orderData['addtime']),
                            'keyword2' => $orderData['goods_name'],
                            'keyword3' => $orderData['bucket_num'],
                            'keyword4' => $orderData['buyer_address'],
                            'keyword5' => $orderData['description'],
                            'remark' => $resend ? ['改派订单，请尽快处理','#cf2d28'] : '请尽快接单送水。',
                        ],
                    ]);
                } catch (\Exception $e) {
                    continue;
                }
            }
        }
//        }

    }

    //订单开始配送（用户）
    public function preSendOrderMsg($orderData)
    {
        if ($_SERVER['SERVER_NAME'] == 'www.gx.tt') {
            return true;
        }
        $member = new Member();
        $memberInfo = $member->_getOne(['id' => $orderData['buyer_id']], 'id,wx_openid');
        $tmpId = $this->tempId['pre_send'];

        $wechatSet = new WechatSet();
        $settings = $wechatSet->_getOne(['admin_id' => 1]);
        if (!$settings) {
            return false;
        }
        config(['wechat.app_id' => $settings['wx_app_id']]);
        config(['wechat.secret' => $settings['wx_app_secret']]);
        config(['wechat.aes_key' => $settings['wx_aes_key']]);
        $wechat = app('wechat');

        $worker = new Worker();
        $workerInfo = $worker->_redisGetOneByWid($orderData['worker_id']);
        // 判断memberInfo['wx_openid'] 是否等于 $orderData['buyer_openid']
        try {
            $sendData = [
                'touser' => $memberInfo['wx_openid'],
                'template_id' => $tmpId,
                'url' => '',
                'data' => [
                    'first' => "您的订单已开始配送",
                    'keyword1' => $orderData['updated_at'],
                    'keyword2' => $workerInfo['name'],
                    'keyword3' => $workerInfo['mobile'],
                    'remark' => '如有问题请电话联系配送师傅，祝您生活愉快。',
                ],
            ];
            if ($memberInfo['wx_openid'] == $orderData['buyer_openid']) {
                $wechat->notice->send($sendData);
            } else {
                if ($memberInfo['wx_openid']) {
                    $wechat->notice->send($sendData);
                }
                if ($orderData['buyer_openid']) {
                    $sendData['touser'] = $orderData['buyer_openid'];
                    $wechat->notice->send($sendData);
                }
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    public function preSendOrderMsgBySys($orderData)
    {
        if ($_SERVER['SERVER_NAME'] == 'www.qds.cn') {
            return true;
        }
        $tmpId = $this->tempId['pre_send'];
        $wechatSet = new WechatSet();
        $settings = $wechatSet->_getOne(['admin_id' => 1]);
        if (!$settings) {
            return false;
        }
        config(['wechat.app_id' => $settings['wx_app_id']]);
        config(['wechat.secret' => $settings['wx_app_secret']]);
        config(['wechat.aes_key' => $settings['wx_aes_key']]);
        $wechat = app('wechat');
        $member = new Member();
        $memberInfo = $member->_getOne(['id' => $orderData['buyer_id']], 'id,wx_openid');
        try {
            $order = new Order();
            $order->_update(['id' => $orderData['id']], ['dispatch' => 1]);
            $shop = new Shop();
            $shopInfo = $shop->_redisGetOneBySid($orderData['shop_id']);
            $sendData = [
                'touser' => $memberInfo['wx_openid'],
                'template_id' => $tmpId,
                'url' => '',
                'data' => [
                    'first' => "您的订单已受理，稍后安排配送",
                    'keyword1' => $orderData['created_at'],
                    'keyword2' => '系统',
                    'keyword3' => $shopInfo['cd_contact'],
                    'remark' => '如有问题请电话联系。',
                ],
            ];
            if ($memberInfo['wx_openid']) {
                $wechat->notice->send($sendData);
            }
            if ($orderData['buyer_openid']) {
                $sendData['touser'] = $orderData['buyer_openid'];
                $wechat->notice->send($sendData);
            }
        } catch (\Exception $e) {
            return false;
        }

    }

    //订单配送完成（用户）
    public function sendCompleteOrderMsg($orderData)
    {
        if ($_SERVER['SERVER_NAME'] == 'www.qds.cn') {
            return true;
        }
        $member = new Member();
        $memberInfo = $member->_getOne(['id' => $orderData['buyer_id']], 'id,wx_openid,total_waterbill_num');
        $tmpId = $this->tempId['com_send'];
        $wechatSet = new WechatSet();
        $settings = $wechatSet->_getOne(['admin_id' => 1]);
        if (!$settings) {
            return false;
        }
        config(['wechat.app_id' => $settings['wx_app_id']]);
        config(['wechat.secret' => $settings['wx_app_secret']]);
        config(['wechat.aes_key' => $settings['wx_aes_key']]);
        $wechat = app('wechat');
        $worker = new Worker();
        $workerInfo = $worker->_redisGetOneByWid($orderData['worker_id']);

        $goods_name = $orderData['order_goods'][0]['goods_name'];
        if (count($orderData['order_goods']) > 1) {
            $goods_name .= '...';
        }
        try {
            $sendData = [
                'touser' => $memberInfo['wx_openid'],
                'template_id' => $tmpId,
                'url' => '',
                'data' => [
                    'first' => "您的订单配送完成。",
                    'keyword1' => $orderData['updated_at'],
                    'keyword2' => $goods_name,
                    'keyword3' => $orderData['bucket_num'],
                    'keyword4' => $orderData['back_bucket_num'],
                    'keyword5' => $memberInfo['total_waterbill_num'],
                    'remark' => '请核对以上信息，如有不实，请电话联系' . $workerInfo['mobile'],
                ],
            ];
            if ($memberInfo['wx_openid']) {
                $wechat->notice->send($sendData);
            }
            if ($orderData['buyer_openid']) {
                $sendData['touser'] = $orderData['buyer_openid'];
                $wechat->notice->send($sendData);
            }
        } catch (\Exception $e) {
            return false;
        }

    }

    /**
     * 发送收款信息
     * @param $orderInfo array 订单信息
     * @param $type int 订单类型：1.零售支付  2.购买水票
     * @return bool
     */
    public function sendReceiveMsg($orderInfo, $type)
    {
        if ($_SERVER['SERVER_NAME'] == 'www.qds.cn') {
            return true;
        }
        if (!in_array($type, [1, 2])) {
            return false;
        }
        $wechatSet = new WechatSet();
        $settings = $wechatSet->_getOne(['admin_id' => 1]);
        if (!$settings) {
            return false;
        }
        config(['wechat.app_id' => $settings['wx_app_id']]);
        config(['wechat.secret' => $settings['wx_app_secret']]);
        config(['wechat.aes_key' => $settings['wx_aes_key']]);

        $shopInfo = (new Shop())->_redisGetOneBySid($orderInfo['shop_id']);
        if (!isset($shopInfo['wx_openid']) || !$shopInfo['wx_openid']) {
            return false;
        }

        $goodsInfo = '';
        if ($type == 1) {
            foreach ($orderInfo['order_goods'] as $v) {
                $goodsInfo .= $v['goods_name'];
            }
            $goodsInfo = trim($goodsInfo, ',');
        } else {
            $goodsInfo = $orderInfo['goods_name'] . "({$orderInfo['title']})";
        }

        if (!$goodsInfo) {
            return false;
        }

        $title = $type == 1 ? '零售' : '购买水票';
        $tmpId = $this->tempId['rec_send'];
        $sendData = [
            'touser' => $shopInfo['wx_openid'],
            'template_id' => $tmpId,
            'url' => '',
            'data' => [
                'first' => "您有一笔交易入账（{$title}）",
                'keyword1' => date('Y-m-d H:i:s'),
                'keyword2' => $orderInfo['order_amount'],
                'keyword3' => $orderInfo['order_sn'],
                'remark' => '购买商品：' . $goodsInfo,
            ],
        ];
        try {
            $wechat = app('wechat');
            $wechat->notice->send($sendData);
        } catch (\Exception $e) {
            return false;
        }

    }

}